import matplotlib.pyplot as plt
from custom import *
from PCA_tools import draw_vocab_pca
from torch import nn
from d2l import torch as d2l
import torch

batch_size, num_steps = 32, 35
train_iter, vocab = d2l.load_data_time_machine(batch_size, num_steps)


# 9.1.2.1. 初始化模型参数
def get_params(embedding_size, vocab_size, num_hiddens, device):
    num_inputs = embedding_size
    num_outputs = vocab_size

    def normal(shape):
        return torch.randn(size=shape, device=device) * 0.01

    def three():
        return (normal((num_inputs, num_hiddens)),
                normal((num_hiddens, num_hiddens)),
                torch.zeros(num_hiddens, device=device))

    # 注意这里一共是11个参数 下面是前面9个
    W_xz, W_hz, b_z = three()  # 更新门参数
    W_xr, W_hr, b_r = three()  # 重置门参数
    W_xh, W_hh, b_h = three()  # 候选隐状态参数
    # 下面是连个输出层参数
    W_hq = normal((num_hiddens, num_outputs))
    b_q = torch.zeros(num_outputs, device=device)
    # 附加梯度
    params = [W_xz, W_hz, b_z, W_xr, W_hr, b_r, W_xh, W_hh, b_h, W_hq, b_q]
    for param in params:
        param.requires_grad_(True)
    return params


# 9.1.2.2. 定义模型
def init_gru_state(batch_size, num_hiddens, device):
    return (torch.zeros((batch_size, num_hiddens), device=device),)


def gru(inputs, state, params):
    W_xz, W_hz, b_z, W_xr, W_hr, b_r, W_xh, W_hh, b_h, W_hq, b_q = params
    H, = state
    outputs = []
    for X in inputs:
        # 32,128 128,256  #32*256#
        Z = torch.sigmoid((X @ W_xz) + (H @ W_hz) + b_z)
        R = torch.sigmoid((X @ W_xr) + (H @ W_hr) + b_r)
        H_tilda = torch.tanh((X @ W_xh) + ((R * H) @ W_hh) + b_h)
        H = Z * H + (1 - Z) * H_tilda
        Y = H @ W_hq + b_q
        outputs.append(Y)

    """
    T=28    时间序列长度
    N=32    batch_size
    D=128   词嵌入长度
    V=932   词表大小
    H=256   隐变量长度
    X [28,32,128]
    Y [896, 932]
    H [32, 256]  
    """
    return torch.cat(outputs, dim=0), (H,)


# 9.1.2.3. 训练与预测
# 加载之前准备好的数据
batch_size, num_steps = 32, 28
num_hiddens = 256
embedding_size = 128
train_iter, vocab = load_data_time_machine(batch_size, num_steps)

vocab_size, num_hiddens, device = len(vocab), 256, d2l.try_gpu()
num_epochs, lr = 500, 1
model = RNNModelScratch(embedding_size, len(vocab), num_hiddens, device, get_params,
                        init_gru_state, gru)
train_ch8(model, train_iter, vocab, lr, num_epochs, device)
print("net.embedding.weight.data 大小", model.embedding.weight.data.shape)

word = "每个"
p_words = predict(word, model, vocab, device)

# 降维度加显示
draw_vocab_pca(model.embedding.weight.data, vocab, dim=3)
plt.show()
